package com.surprise.db.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import com.surprise.db.po.Admin;

import lombok.AllArgsConstructor;

@Repository
public class AdminDAO extends SimpleDAO<Admin> {
    public final String columns = "(username, password, portrait, phone, role, type, addtime)";
    public final String insertStatement = "(?,?,?,?,?,?,now())";
    
    @AllArgsConstructor
    public static class AdminSetter implements BatchPreparedStatementSetter {
        private List<Admin> items;
        
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Admin item = items.get(i);
            int index = 1;
            ps.setString(index++, item.getUsername());
            ps.setString(index++, item.getPassword());
            ps.setString(index++, item.getPortrait());
            ps.setString(index++, item.getPhone());
            ps.setInt(index++, item.getRole());
            ps.setInt(index++, item.getType());
        }

        @Override
        public int getBatchSize() {
            return items.size();
        }
    }
    
    public int add(final Admin item) {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into ").append(getTableName()).append(columns).append(insertStatement);
        String sql = sb.toString();
        return jdbcTemplate.update(sql, new PreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                int index = 1;
                ps.setString(index++, item.getUsername());
                ps.setString(index++, item.getPassword());
                ps.setString(index++, item.getPortrait());
                ps.setString(index++, item.getPhone());
                ps.setInt(index++, item.getRole());
                ps.setInt(index++, item.getType());
            }
        });
    }
    
    public void add(List<Admin> items) {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into ").append(getTableName()).append(columns).append(insertStatement);
        String sql = sb.toString();
        jdbcTemplate.batchUpdate(sql, new AdminSetter(items));
    }
    
    public Admin findByPhone(String phone) {
        String sql = "select * from #table# where phone = ?";
        List<Admin> ret = findBySql(sql, phone);
        if(CollectionUtils.isEmpty(ret)) {
            return null;
        }
        return ret.get(0);
    }
}
